package com.training.admin.web.controller.projectdata;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.DateUtils;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.training.admin.entity.project.Project;
import com.training.admin.entity.project.ProjectPhase;
import com.training.admin.entity.project.ProjectPhaseCourse;
import com.training.admin.entity.project.ProjectTrainee;
import com.training.admin.entity.trainer.Trainer;
import com.training.admin.service.DataService;
import com.training.admin.service.ProjectDataService;
import com.training.admin.service.ProjectPhaseCourseService;
import com.training.admin.service.ProjectPhaseService;
import com.training.admin.service.ProjectTraineeService;
import com.training.admin.web.controller.view.ExcelTemplateView;

/**
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/project-data")
@MenuSetting("menu-training-project")
public class ProjectDataViewController {
	
	private static final Logger logger = LoggerFactory.getLogger(ProjectDataViewController.class);

	@Autowired
	private ProjectDataService projectDataService;
	
	@Autowired
	private ProjectPhaseService projectPhaseService;
	
	@Autowired
	private ProjectPhaseCourseService projectPhaseCourseService;
	
	@Autowired
	private ProjectTraineeService projectTraineeService;

	@Autowired
	@Qualifier("dataService")
	private DataService<Trainer> trainerService;
	
	
	/**
	 * 
	 * @param project
	 */
	private void updateProjectDate(Project project) {
		
		List<ProjectPhase> projectPhaseList = projectPhaseService.listByProjectId(project.getId());
		
		if(CollectionUtils.isNotEmpty(projectPhaseList)) {
			Date minDate = projectPhaseList.get(0).getBeginDate();
			minDate = minDate == null ? new Date() : minDate;
			Date maxDate = projectPhaseList.get(0).getEndDate();
			maxDate = maxDate == null ? new Date() : maxDate;
			for (int i = 0; i < projectPhaseList.size(); i++) {
				Date startDate = projectPhaseList.get(i).getBeginDate();
				Date endDate = projectPhaseList.get(i).getEndDate();
				minDate = startDate == null ? minDate: (startDate.before(minDate) ? startDate : minDate);
				maxDate = endDate == null ? maxDate : (endDate.after(maxDate) ? endDate : maxDate);
			}
			
			project.setBeginDate(minDate);
			project.setEndDate(maxDate);
			projectDataService.update(project);
		}
	}
	
	/**
	 * 项目详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
	@MenuSetting("submenu-project-data-management")
	public ModelAndView view(@PathVariable("id") Long id,String currentPhase, String filePath, Page page) {

		ModelAndView modelAndView = new ModelAndView("project-data/project-data-view");
		// get project detail
		Project project = projectDataService.load(Project.class, id);
		// get project phases
		List<ProjectPhase> projectPhaseList = projectPhaseService.listByProjectId(id);
		// set default phase to display
		if (currentPhase == null || currentPhase.trim().length() == 0) {
			currentPhase = "1";
		}
		Long currentPhaseId = null;
		// get porjuect phase courses
		Map<Long, List<ProjectPhaseCourse>> projectPhaseCourseMap = new HashMap<Long, List<ProjectPhaseCourse>>();
		for (int i = 0; i < projectPhaseList.size(); i++) {
			ProjectPhase projectPhase = projectPhaseList.get(i);
			List<ProjectPhaseCourse> projectPhaseCouseList = projectPhaseCourseService
					.listByProjectPhaseId(projectPhase.getId());
			projectPhaseCourseMap.put(projectPhase.getId(), projectPhaseCouseList);
			if (Integer.parseInt(currentPhase) == projectPhase.getPhase()) {
				currentPhaseId = projectPhase.getId();
			}
		}
		// get trainee by page
		int totals = projectTraineeService.countByProjectId(id);
		List<ProjectTrainee> projectTraineeList = projectTraineeService.listByProjectId(id, page.with(totals));
		page.calculate();
		
		if(filePath != null) {
			modelAndView.addObject("filePath", filePath);
		}
		modelAndView.addObject("currentPhase", currentPhase);
		modelAndView.addObject("currentPhaseId", currentPhaseId);
		modelAndView.addObject("project", project);
		modelAndView.addObject("projectPhases", projectPhaseList);
		modelAndView.addObject("projectPhaseCouseMap", projectPhaseCourseMap);
		modelAndView.addObject("projectTrainees", projectTraineeList);
		modelAndView.addObject("page", page);
		return modelAndView;
	}
	
	

	

	
	
	/**
	 * 修改当期时间
	 * 
	 * @param phaseId
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/{phaseId}/phase-date-edit", method = RequestMethod.GET)
	@MenuSetting("submenu-project-data-management")
	public ModelAndView editPhaseDate(@PathVariable("phaseId") Long phaseId, Page page) {
		ModelAndView modelAndView = new ModelAndView("project-data/project-data-phase-date-edit");
		
		ProjectPhase projectPhase = projectPhaseService.load(ProjectPhase.class, phaseId);
		modelAndView.addObject("projectPhase", projectPhase);
		
		return modelAndView;
	}

	/**
	   *    修改日期提交
	 * 
	 * @param projectPhaseId
	 * @param selectedCourseId
	 * @return
	 */
	@RequestMapping(value = "/{projectId}/phase-date-edit", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-project-data-management")
	public @ResponseBody HttpResult onEditPhaseDate(HttpServletRequest request, @RequestParam Long projectPhaseId,
			@RequestParam String beginDate, @RequestParam String endDate, @RequestParam String currentPhase) {
		HttpResult httpResult = new HttpResult();
		try {
			
		    ProjectPhase projectPhase = projectPhaseService.load(ProjectPhase.class, projectPhaseId);
			projectPhaseService.update(projectPhase.editDate(DateUtils.parseDate(beginDate, "yyyy-MM-dd"), DateUtils.parseDate(endDate, "yyyy-MM-dd")));
			
			updateProjectDate(projectPhase.getProject());
			
			httpResult.success().message("修改日期成功");

		} catch (Exception e) {
			httpResult.fail("500").message("修改日期失败! " + e.getMessage());
			logger.error("#onEditPhaseDate() - add course fail, exception is [{}]", e);
		}

		return httpResult;

	}
	
	/**
	 * 
	 * @param projectId
	 * @return
	 */
	@RequestMapping(value="/{projectId}/project-score-template", method = RequestMethod.GET)
	public ModelAndView scoreExport(@PathVariable("projectId") Long projectId) {
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("project-trainee-score-result.xls"));
        
        List<ProjectTrainee> projectTraineeList = projectTraineeService.listByProjectId(projectId);
        modelAndView.addObject("projectTrainees", projectTraineeList);
        
        return modelAndView;
    }
	
	/**
     * 
     * @param projectId
     * @return
     */
    @RequestMapping(value="/{projectId}/project-attendance-template", method = RequestMethod.GET)
    public ModelAndView attendanceExport(@PathVariable("projectId") Long projectId) {
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("project-trainee-attendance-result.xls"));
        
        List<ProjectTrainee> projectTraineeList = projectTraineeService.listByProjectId(projectId);
        modelAndView.addObject("projectTrainees", projectTraineeList);
        
        return modelAndView;
    }
}
